package com.onmicro.snc_ble.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.onmicro.snc_ble.R;
import com.onmicro.snc_ble.adpter.GroupedTabBarItemAdapter;
import com.onmicro.snc_ble.app.App;
import com.onmicro.snc_ble.common.PreferenceUtils;
import com.onmicro.snc_ble.core.bluetooth.BluetoothManager;
import com.onmicro.snc_ble.core.bluetooth.OmrBluetoothManager;
import com.onmicro.snc_ble.core.db.DBGroup;
import com.onmicro.snc_ble.core.voice.SpeechManager;
import com.onmicro.snc_ble.dialog.EnterAppDialog;
import com.onmicro.snc_ble.dialog.PopupMenu.PopupMenu;
import com.onmicro.snc_ble.dialog.PopupMenu.PopupMenuItem;
import com.onmicro.snc_ble.dialog.SetModelDialog;
import com.onmicro.snc_ble.dialog.SweetAlertDialog;
import com.onmicro.snc_ble.models.GroupModel;
import com.onmicro.snc_ble.view.BrightnessCircularSlider;
import com.onmicro.snc_ble.view.ColorPickerView;
import com.onmicro.snc_ble.view.ColorTempCircularSliderView;
import com.onmicro.snc_ble.view.FanImageView;
import com.onmicro.snc_ble.view.MoreModesView;
import com.onmicro.snc_ble.view.PickerView;
import com.jaeger.library.StatusBarUtil;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.iwgang.countdownview.CountdownView;

/**
 * @author peng
 */
public class MainActivity extends BaseActivity {
    private static final String PREFERENCE_MODEL_NAME = "supportModel";

    @BindView(R.id.title_bar)
    ConstraintLayout actionBar;

    @BindView(R.id.backBarButton)
    ImageButton backBarButton;

    @BindView(R.id.backgroundView)
    ConstraintLayout backgroundView;

    @BindView(R.id.brightnessSeekBar)
    SeekBar brightnessSeekBar;

    @BindView(R.id.brightnessCircularSlider)
    BrightnessCircularSlider brightnessSlider;

    @BindView(R.id.brightness_text)
    TextView brightnessText;

    @BindView(R.id.close_text)
    TextView closeText;

    @BindView(R.id.colorPickerView)
    ColorPickerView colorPickerView;

    @BindView(R.id.colorTempCircularSliderView)
    ColorTempCircularSliderView colorTempView;

    @BindView(R.id.fanBackgroundView)
    View fanBackgroundView;

    @BindView(R.id.fan_brightness_text)
    TextView fanBrightnessText;

    @BindView(R.id.fanImageView)
    FanImageView fanImageView;

    @BindView(R.id.fanMoreModesView)
    MoreModesView fanMoreModesView;

    @BindView(R.id.fan_pair_text)
    TextView fanPairText;

    @BindView(R.id.fanSeekBar)
    SeekBar fanSeekBar;

    @BindView(R.id.fanSwitchImage)
    ImageView fanSwitchImage;

    @BindView(R.id.fan_switch_text)
    TextView fanSwitchText;

    @BindView(R.id.fan_text)
    TextView fanText;

    @BindView(R.id.fan_voice_text)
    TextView fanVoiceText;

    @BindView(R.id.groupedTabBarView)
    RecyclerView groupedTabBarView;

    @BindView(R.id.high_text)
    TextView highText;

    @BindView(R.id.in_text)
    TextView inText;
    @BindView(R.id.leftBarButton)
    Button leftBarButton;

    @BindView(R.id.low_text)
    TextView lowText;

    @BindView(R.id.message_left_text)
    TextView messageLeftText;

    @BindView(R.id.message_right_text)
    TextView messageRightText;

    @BindView(R.id.message_view)
    LinearLayout messageView;

    @BindView(R.id.moreModesView)
    MoreModesView moreModesView;

    @BindView(R.id.pair_text)
    TextView pairText;

    @BindView(R.id.recognizer_view)
    AVLoadingIndicatorView recognizerView;

    @BindView(R.id.rightBarButton)
    ImageButton rightBarButton;

    @BindView(R.id.switchImage)
    ImageView switchImage;

    @BindView(R.id.switch_text)
    TextView switchText;

    @BindView(R.id.text_title)
    TextView textTitle;

    @BindView(R.id.timerview)
    CountdownView timerView;

    @BindView(R.id.voice_text)
    TextView voiceText;

    @BindView(R.id.voice_view)
    ConstraintLayout voiceView;

    private List<GroupModel> dataSource = new ArrayList<>();

    private GroupModel groupModel;

    private GroupedTabBarItemAdapter groupedAdapter;

    private boolean isCurrentRunningForeground = true;

    private PopupMenu popupMenu;

    private int selectIndex = 0;

    private String mSupportMoudel;

    private byte[] mOmrRfData;

    private byte[] mOmrRfAddr = {(byte) 0x98, 0x43, (byte) 0xaf, 0x0b, 0x46};

    private int mOmrTimeOut = 0 * 10 * 1000; // ms

    private OmrBluetoothManager mOmrBluetoothManager;

    private SeekBar.OnSeekBarChangeListener onFanSeekBarChange = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            int round = StrictMath.round(seekBar.getProgress() / 10);
            fanRotate(round);
        }
    };

    private SeekBar.OnSeekBarChangeListener onbrightnessSeekBarChange = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                beganUpdateBrightness(seekBar.getProgress());
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            endedUpdateBrightness(seekBar.getProgress());
        }
    };


    private PopupMenu.OnItemOnClickListener onItemOnClickListener = new PopupMenu.OnItemOnClickListener() {
        @Override
        public void onItemClick(PopupMenuItem param1PopupMenuItem, int param1Int) {
            Intent intent;
            switch (param1Int) {
                case 0:
                    new SweetAlertDialog(MainActivity.this)
                            .setTitleText(getString(R.string.tip))
                            .setContentText(getString(R.string.tip_msg_clear))
                            .setCancelText(getString(R.string.cancel))
                            .setConfirmClickListener(param1SweetAlertDialog -> {
                                // ble
                                if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                                    // mesh
                                    BluetoothManager.getInstance().clearCode();
                                } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                                    // Onmicro
                                    mOmrBluetoothManager.clearCode();
                                }
                                showToast("清除设备码");
                            }).show();
                    break;
                case 1:
                    intent = new Intent(MainActivity.this, GroupedMgtTableActivity.class);
                    startActivityForResult(intent, 10);
                    break;
                default:
                    /*
                    new SetModelDialog(MainActivity.this)
                            .setTitleText(getString(R.string.tip))
                            .setCancelText(getString(R.string.cancel))
                            .setConfirmClickListener(mode -> {
                                if (!mSupportMoudel.equals(mode)) {
                                    mSupportMoudel = mode;
                                    PreferenceUtils.putValue(App.getInstance(), PREFERENCE_MODEL_NAME, mSupportMoudel);
                                    if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                                        // ZJ
                                        BluetoothManager.getInstance();
                                    } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                                        // Onmicro
                                        mOmrBluetoothManager = OmrBluetoothManager.getInstance();
                                    }
                                    initializeDataSource();
                                    loadDataSource();
                                }
                            }).show();
                    */
                    break;
            }
        }
    };

    private ColorPickerView.OnPickerSaturationListener onPickerSaturationListener = new ColorPickerView.OnPickerSaturationListener() {
        @Override
        public void onBeganPickerSaturation(double param1Double1, double param1Double2) {
            beganUpdateColorTemp((float) param1Double1);
        }

        @Override
        public void onEndedPickerSaturation(double param1Double1, double param1Double2) {
            endedUpdateColorTemp((float) param1Double1);
        }
    };

    private MoreModesView.OnSelectMoreModesListener onSelectMoreModesListener = new MoreModesView.OnSelectMoreModesListener() {
        @Override
        public void onSelectMoreModesAtIndex(MoreModesView param1MoreModesView, int param1Int) {
            if (param1Int == 5) {
                pickerTime();
                return;
            }
            groupModel.setFeaturesIndex(param1Int);
            DBGroup.updateFeatures(MainActivity.this.groupModel);
            selectMoreModes(param1Int, groupModel.getStyle());
            if (param1Int == 11) {
                fanRotateData(0);
            }

            if (param1MoreModesView == moreModesView) {
                // ble
                if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                    BluetoothManager.getInstance().setMoreModes(param1Int);
                } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                    // Onmicro
                    mOmrBluetoothManager.setMoreModes(param1Int);
                }
            }
            // ble
            if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                BluetoothManager.getInstance().setFanMoreModes(param1Int);
            } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                // Onmicro
                mOmrBluetoothManager.setFanMoreModes(param1Int);
            }
        }
    };

    private BrightnessCircularSlider.OnUpdateBrightnessListener onUpdateBrightnessListener = new BrightnessCircularSlider.OnUpdateBrightnessListener() {
        @Override
        public void onBeganUpdateBrightness(float param1Float) {
            beganUpdateBrightness(param1Float);
        }

        @Override
        public void onEndedUpdateBrightness(float param1Float) {
            endedUpdateBrightness(param1Float);
        }
    };

    private ColorTempCircularSliderView.OnUpdateColorTempListener onUpdateColorTempListener = new ColorTempCircularSliderView.OnUpdateColorTempListener() {
        @Override
        public void onBeganUpdateColorTemp(float param1Float) {
            beganUpdateColorTemp(param1Float);
        }

        @Override
        public void onEndedUpdateColorTemp(float param1Float) {
            endedUpdateColorTemp(param1Float);
        }
    };

    /**
     * TODO: oncreate method
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        actionBar.setBackgroundColor(getResources().getColor(R.color.clearColor));
        backBarButton.setVisibility(View.GONE);
        leftBarButton.setVisibility(View.VISIBLE);
        rightBarButton.setVisibility(View.VISIBLE);
        colorPickerView.setOnPickerSaturationListener(onPickerSaturationListener);
        colorTempView.setOnUpdateColorTempListener(onUpdateColorTempListener);
        fanSeekBar.setOnSeekBarChangeListener(onFanSeekBarChange);
        brightnessSlider.setOnUpdateBrightnessListener(onUpdateBrightnessListener);
        brightnessSeekBar.setOnSeekBarChangeListener(onbrightnessSeekBarChange);
        moreModesView.setOnSelectMoreModesListener(onSelectMoreModesListener);
        fanMoreModesView.setOnSelectMoreModesListener(onSelectMoreModesListener);
        switchImage.setOnTouchListener(new OnSwitchTouchListener());
        fanSwitchImage.setOnTouchListener(new OnSwitchTouchListener());
        StatusBarUtil.setTransparent(this);

        requestPermissions();
        initPopWindow();
        initializeDataSource();
        addGroupedTabBarView();
        loadDataSource();

        Boolean isShow = PreferenceUtils.getBooleanValue(App.getInstance(), "checkbox_show");

        mSupportMoudel = PreferenceUtils.getValue(App.getInstance(), PREFERENCE_MODEL_NAME);
        if (mSupportMoudel.isEmpty()) {
            mSupportMoudel = SetModelDialog.MESH_MODEL;
            mSupportMoudel = SetModelDialog.TRADITIONAL_MODEL;
        }

        if (mSupportMoudel.equals(SetModelDialog.MESH_MODEL)) {
            BluetoothManager.getInstance();
            if (isShow) {
                new EnterAppDialog(this)
                        .setContentText("当前使用的是原始蓝牙")
                        .show();
            }
        } else if (mSupportMoudel.equals(SetModelDialog.TRADITIONAL_MODEL)) {
            // Onmicro
            mOmrBluetoothManager = OmrBluetoothManager.getInstance();
            if (isShow) {
                new EnterAppDialog(this)
                        .setContentText("当前使用的是昂瑞微蓝牙")
                        .show();
            }
        }
        updateText();
    }

    private void showDialog(String message) {
        new SweetAlertDialog(this)
                .setTitleText(getString(R.string.tip))
                .setContentText(message)
                .setCancelText(getString(R.string.cancel))
                .setConfirmText(getString(R.string.confirm))
                .show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isCurrentRunningForeground) {
            SpeechManager.getInstance().resumeSpeech();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isCurrentRunningForeground = isRunningForeground();
        if (isCurrentRunningForeground) {
            SpeechManager.getInstance().pauseSpeech();
        }
    }

    @Override
    protected void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent) {
        super.onActivityResult(paramInt1, paramInt2, paramIntent);
        if (paramInt1 != 10 && paramIntent != null) {
            String str = paramIntent.getStringExtra("groupName");
            paramInt1 = paramIntent.getIntExtra("style", 0);
            if (str != null && str.length() != 0) {
                addNewGroup(str, paramInt1);
            }

        } else if (paramIntent != null && paramIntent.getBooleanExtra("change", false)) {
            loadDataSource();
        }
    }

    /**
     * leftBarButton click
     */
    public void onClickedLeftBarButtonAction(View paramView) {
        groupModel.setTimeInterval(0L);
        DBGroup.updateGroup(this.groupModel);
        updateTiming(0L);
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setCancelTiming(0, 0, 0);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setCancelTiming(0, 0, 0);
        }
    }

    /**
     * rightBarButton click
     */
    public void onClickedRightBarButtonAction(View paramView) {
        popupMenu.show(actionBar);
    }

    /**
     * connectionButton click
     */
    public void onConnectionButtonClicked(View paramView) {
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().pairCode();
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.pairCode();
        }
    }


    /**
     * voiceButton click
     */
    public void onVoiceButtonClicked(View paramView) {
        voiceView.setVisibility(View.VISIBLE);
        SpeechManager.getInstance().startSpeaking("您好我在", groupModel.getStyle(), new SpeechManager.SpeechCallback() {
            @Override
            public void onBrightness(int param1Int) {
                if (groupModel.getStyle() == GroupModel.GROUPED_STYLE_ADD_FAN) {
                    brightnessSeekBar.setProgress(param1Int);
                } else {
                    brightnessSlider.reloadBrightnessSlider(param1Int);
                }
                endedUpdateBrightness(param1Int);
            }

            @Override
            public void onCompleted(int param1Int) {
                switch (param1Int) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        // 猜测这个位置
                        groupModel.setFeaturesIndex(param1Int);
                        DBGroup.updateFeatures(groupModel);
                        selectMoreModes(param1Int, groupModel.getStyle());
                        if (groupModel.getStyle() == GroupModel.GROUPED_STYLE_ADD_FAN) {
                            fanMoreModesView.scrollToMoreModesAtIndex(groupModel.getFeaturesIndex());
                            if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                                BluetoothManager.getInstance().setFanMoreModes(param1Int);
                            } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                                // Onmicro
                                mOmrBluetoothManager.setFanMoreModes(param1Int);
                            }
                            return;
                        }
                        moreModesView.scrollToMoreModesAtIndex(groupModel.getFeaturesIndex());
                        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                            BluetoothManager.getInstance().setMoreModes(param1Int);
                        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                            // Onmicro
                            mOmrBluetoothManager.setMoreModes(param1Int);
                        }
                        break;
                    case 5:
                        groupModel.setIsOn(true);
                        DBGroup.updateGroup(groupModel);
                        updateSwitch(groupModel.getIsOn());
                        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                            BluetoothManager.getInstance().open();
                        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                            // Onmicro
                            mOmrBluetoothManager.open();
                        }
                        break;
                    case 6:
                        groupModel.setIsOn(false);
                        DBGroup.updateGroup(MainActivity.this.groupModel);
                        updateSwitch(groupModel.getIsOn());
                        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                            BluetoothManager.getInstance().close();
                        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                            // Onmicro
                            mOmrBluetoothManager.close();
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onFan(int param1Int) {
                switch (param1Int) {
                    case 0:
                        fanRotate(1);
                        break;
                    case 1:
                        fanRotate(2);
                        break;
                    case 2:
                    case 3:
                        fanRotate(3);
                        break;
                    case 4:
                        groupModel.setFeaturesIndex(11);
                        DBGroup.updateFeatures(groupModel);
                        fanMoreModesView.scrollToMoreModesAtIndex(groupModel.getFeaturesIndex());
                        fanRotateData(0);
                        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                            BluetoothManager.getInstance().setFanMoreModes(11);
                        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                            // Onmicro
                            mOmrBluetoothManager.setFanMoreModes(11);
                        }

                        break;
                    case 5:
                        fanRotate(0);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onMessage(String param1String1, String param1String2) {
                newMessage(param1String1, param1String2);
            }

            @Override
            public void onVolumeChanged(int param1Int) {
                recognizerView.setVisibility(View.VISIBLE);
                messageView.setVisibility(View.GONE);
            }

            @Override
            public void endSpeech() {
                recognizerView.setVisibility(View.GONE);
                messageView.setVisibility(View.VISIBLE);
            }
        });

        newMessage("您好我在", "");
    }

    /**
     * stop_button clicked
     */
    public void stopVoiceButtonClicked(View paramView) {
        recognizerView.hide();
        voiceView.setVisibility(View.GONE);
        SpeechManager.getInstance().stopSpeech();

    }


    private void initPopWindow() {
        popupMenu = new PopupMenu(this, -2, -2);
        popupMenu.setItemOnClickListener(onItemOnClickListener);
        popupMenu.addMenuItem(new PopupMenuItem(this, getString(R.string.pop_device_reset), R.mipmap.popmenu_add_delete));
        popupMenu.addMenuItem(new PopupMenuItem(this, getString(R.string.pop_group_edit), R.mipmap.popmenu_add_mgt));
        popupMenu.addMenuItem(new PopupMenuItem(this, getString(R.string.settings), R.mipmap.popmenu_add_settings));
    }

    private void initializeDataSource() {
        if (!DBGroup.selectExistGroupsStyle(9)) {
            GroupModel groupModel1 = newGroupModel();
            groupModel1.setGroupId("FF");
            groupModel1.setGroupName("总控");
            groupModel1.setIsSelected(true);
            groupModel1.setStyle(GroupModel.GROUPED_STYLE_MASTER_CONTROL);
            DBGroup.insertGroupModel(groupModel1);
        }
        if (PreferenceUtils.getIntValue(this, "RUN_COUNT") == 0) {
            PreferenceUtils.putIntValue(this, "RUN_COUNT", 1);
            GroupModel groupModel1 = newGroupModel();
            groupModel1.setGroupId("01");
            groupModel1.setGroupName(getString(R.string.grouped_style008));
            groupModel1.setStyle(GroupModel.GROUPED_STYLE_ADD_FAN);
            DBGroup.insertGroupModel(groupModel1);
            groupModel1 = newGroupModel();
            groupModel1.setGroupId("02");
            groupModel1.setGroupName(getString(R.string.grouped_style000));
            groupModel1.setStyle(GroupModel.GROUPED_STYLE_WIVIN_GROOM);
            DBGroup.insertGroupModel(groupModel1);
        }
    }

    private void updateText() {
        setTitle(getString(R.string.app_name));
        brightnessText.setText(R.string.brightness_adj);
        pairText.setText(R.string.pair_code);
        switchText.setText(R.string.switch_title);
        voiceText.setText(R.string.voice);
        closeText.setText(R.string.close);
        lowText.setText(R.string.low);
        inText.setText(R.string.in);
        highText.setText(R.string.high);
        fanText.setText(R.string.fan_adj);
        fanBrightnessText.setText(R.string.brightness_adj);
        fanPairText.setText(R.string.pair_code);
        fanSwitchText.setText(R.string.switch_title);
        fanVoiceText.setText(R.string.voice);
    }

    private void addGroupedTabBarView() {
        groupedAdapter = new GroupedTabBarItemAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        groupedTabBarView.setLayoutManager(linearLayoutManager);
        groupedTabBarView.setAdapter(groupedAdapter);
        groupedAdapter.setOnItemClickListener((param1BaseQuickAdapter, param1View, param1Int) -> {
            GroupModel groupModel = dataSource.get(param1Int);
            if (groupModel.getStyle() != GroupModel.GROUPED_STYLE_ADD_GROUP) {
                GroupModel groupModel1 = dataSource.get(selectIndex);
                groupModel1.setIsSelected(Boolean.FALSE);
                DBGroup.updateSelectedGroup(groupModel1);
                groupModel.setIsSelected(Boolean.TRUE);
                DBGroup.updateSelectedGroup(groupModel);
                groupedAdapter.setNewData(dataSource);
                onSelectItemAtGroup(groupModel, param1Int);
                return;
            }
            onAddGroupClicked();
        });
    }

    class OnSwitchTouchListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                boolean bool = false;
                boolean b = (v == switchImage) ? (event.getX() > switchImage.getPivotX()) : (event.getX() > fanSwitchImage.getPivotX());
                if (b) {
                    bool = true;
                }
                groupModel.setIsOn(bool);
                DBGroup.updateGroup(groupModel);
                updateSwitch(bool);
                if (bool) {
                    if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                        BluetoothManager.getInstance().open();
                    } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                        mOmrBluetoothManager.open();
                    }

                } else {
                    if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                        BluetoothManager.getInstance().close();
                    } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                        // Onmicro
                        mOmrBluetoothManager.close();
                    }
                }
            }
            return true;
        }
    }

    private void fanRotate(int paramInt) {
        fanRotateData(paramInt);
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setFanIndex(paramInt);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setFanIndex(paramInt);
        }
    }

    private void fanRotateData(int paramInt) {
        fanRotateAnimation(paramInt);
        paramInt *= 10;
        fanSeekBar.setProgress(paramInt);
        groupModel.setSpeed(paramInt);
        DBGroup.updateGroup(this.groupModel);
    }

    private void fanRotateAnimation(int paramInt) {
        // 0 1 2
        switch (paramInt) {
            case SeekBar.AUTOFILL_TYPE_NONE:
                fanImageView.cancelRotateAnimation();
                break;
            case SeekBar.AUTOFILL_TYPE_TEXT:
                fanImageView.startRotateAnimation(800);
                break;
            case SeekBar.AUTOFILL_TYPE_TOGGLE:
                fanImageView.startRotateAnimation(650);
                break;
            default:
                fanImageView.startRotateAnimation(500);
                break;
        }
    }

    private void beganUpdateBrightness(float paramFloat) {
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setBeganBrightness((int) paramFloat);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setBeganBrightness((int) paramFloat);
        }
    }

    private void beganUpdateColorTemp(float paramFloat) {
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setBeganColorTemperature((int) paramFloat);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setBeganColorTemperature((int) paramFloat);
        }
    }


    private void endedUpdateBrightness(float paramFloat) {
        groupModel.setBrightness(paramFloat);
        DBGroup.updateBrightness(this.groupModel);
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setEndedBrightness((int) paramFloat);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setEndedBrightness((int) paramFloat);
        }
    }

    private void endedUpdateColorTemp(float paramFloat) {
        groupModel.setColorTemp(paramFloat);
        DBGroup.updateGroup(this.groupModel);
        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
            BluetoothManager.getInstance().setEndedColorTemperature((int) paramFloat);
        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
            // Onmicro
            mOmrBluetoothManager.setEndedColorTemperature((int) paramFloat);
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void pickerTime() {
        new PickerView(this)
                .setTitleText(getString(R.string.tip_time))
                .setCancelText(getString(R.string.cancel))
                .setConfirmText(getString(R.string.confirm))
                .setConfirmClickListener((param1String1, param1String2, param1String3, param1Long) -> {
                    if (param1Long >= 3000) {
                        param1Long = System.currentTimeMillis() + param1Long;
                        groupModel.setTimeInterval(param1Long);
                        DBGroup.updateGroup(groupModel);
                        updateTiming(param1Long);
                        if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                            BluetoothManager.getInstance().setTiming(Integer.parseInt(param1String1), Integer.parseInt(param1String2), Integer.parseInt(param1String3));
                        } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                            // Onmicro
                            mOmrBluetoothManager.setTiming(Integer.parseInt(param1String1), Integer.parseInt(param1String2), Integer.parseInt(param1String3));
                        }
                    }
                }).show();
    }

    private void selectMoreModes(int param1Int, int style) {
        if (param1Int > 3) {
            return;
        }
        float f1 = 500.0F;
        float f4 = 1000.0F;
        float f2 = f1;
        float f3 = f4;
        switch (param1Int) {
            default:
                f2 = 0.0F;
            case 3:
                f3 = 0.0F;
                f1 = f2;
                break;
            case 1:
                f1 = 0.0F;
                f3 = f4;
                break;
            case 0:
                f1 = 1000.0F;
                f3 = f4;
                break;
            case 2:
                break;
        }
        if (style != GroupModel.GROUPED_STYLE_ADD_FAN) {
            colorPickerView.setColorTemp(f1);
            brightnessSlider.reloadBrightnessSlider(f3);
            return;
        }
        colorTempView.reloadColorTempSlider(f1);
        brightnessSeekBar.setProgress((int) f3);
    }

    private void updateTiming(Long paramLong) {
        paramLong -= System.currentTimeMillis();
        if (paramLong > 0) {
            openTiming(true);
            timerView.start(paramLong);
            timerView.setOnCountdownEndListener(cv -> {
                openTiming(false);
            });
        } else {
            openTiming(false);
        }
    }

    private void openTiming(boolean paramBoolean) {
        timerView.stop();
        if (paramBoolean) {
            leftBarButton.setVisibility(View.VISIBLE);
            timerView.setVisibility(View.VISIBLE);
            textTitle.setVisibility(View.GONE);
        } else {
            leftBarButton.setVisibility(View.GONE);
            timerView.setVisibility(View.GONE);
            textTitle.setVisibility(View.VISIBLE);
        }
    }

    private void updateSwitch(boolean paramBoolean) {
        if (paramBoolean) {
            switchImage.setImageResource(R.mipmap.switch_on);
            fanSwitchImage.setImageResource(R.mipmap.switch_on);
        } else {
            switchImage.setImageResource(R.mipmap.switch_off);
            fanSwitchImage.setImageResource(R.mipmap.switch_off);
        }
    }

    private void onSelectItemAtGroup(GroupModel paramGroupModel, int paramInt) {
        if (paramGroupModel != null) {
            if (paramGroupModel.getStyle() == GroupModel.GROUPED_STYLE_ADD_FAN) {
                backgroundView.setVisibility(View.GONE);
                fanBackgroundView.setVisibility(View.VISIBLE);
                colorTempView.reloadColorTempSlider(paramGroupModel.getColorTemp());
                brightnessSeekBar.setProgress((int) paramGroupModel.getBrightness());
                fanSeekBar.setProgress((int) paramGroupModel.getSpeed());
                fanRotateAnimation(StrictMath.round(paramGroupModel.getSpeed() / 10.0F));
            } else {
                backgroundView.setVisibility(View.VISIBLE);
                fanBackgroundView.setVisibility(View.GONE);
                colorPickerView.setColorTemp(paramGroupModel.getColorTemp());
                brightnessSlider.reloadBrightnessSlider(paramGroupModel.getBrightness());
                fanRotateAnimation(0);
            }
            groupModel = paramGroupModel;
            selectIndex = paramInt;
            if (SetModelDialog.MESH_MODEL.equals(mSupportMoudel)) {
                BluetoothManager.getInstance().setGroupId(paramGroupModel.getGroupId());
            } else if (SetModelDialog.TRADITIONAL_MODEL.equals(mSupportMoudel)) {
                // Onmicro
                mOmrBluetoothManager.setGroupId(paramGroupModel.getGroupId());
            }
            updateTiming(paramGroupModel.getTimeInterval());
            moreModesView.scrollToMoreModesAtIndex(paramGroupModel.getFeaturesIndex());
            updateSwitch(paramGroupModel.getIsOn());

        }
    }

    private void onAddGroupClicked() {
        if (dataSource.size() >= 10) {
            showDialog(getString(R.string.tip_msg_group_max));
            return;
        }
        startActivityForResult(new Intent(this, AddGroupActivity.class), 20);
        overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
    }

    private void loadDataSource() {
        dataSource = DBGroup.selectAllGroups();
        GroupModel groupModel1 = newGroupModel();
        groupModel1.setGroupId("00");
        groupModel1.setGroupName("添加");
        groupModel1.setStyle(GroupModel.GROUPED_STYLE_ADD_GROUP);
        dataSource.add(groupModel1);
        groupedAdapter.replaceData(dataSource);
        boolean bool = false;
        for (byte b = 0; b < dataSource.size(); b++) {
            GroupModel groupModel2 = dataSource.get(b);
            if (groupModel2.getIsSelected()) {
                bool = true;
                onSelectItemAtGroup(groupModel2, b);
            }
        }
        if (dataSource.size() > 0 && !bool) {
            GroupModel groupModel2 = dataSource.get(0);
            groupModel2.setIsSelected(true);
            DBGroup.updateSelectedGroup(groupModel2);
            onSelectItemAtGroup(groupModel2, 0);
        }
    }

    private void newMessage(String paramString1, String paramString2) {
        recognizerView.setVisibility(View.GONE);
        messageView.setVisibility(View.VISIBLE);
        messageLeftText.setText(paramString1);
        messageRightText.setText(paramString2);
    }

    private void addNewGroup(String paramString, int paramInt) {
        GroupModel groupModel1 = newGroupModel();
        groupModel1.setGroupId(generateGroupId());
        groupModel1.setGroupName(paramString);
        groupModel1.setStyle(paramInt);
        paramInt = Math.max(0, dataSource.size() - 1);
        dataSource.add(paramInt, groupModel1);
        DBGroup.insertGroupModel(groupModel1);
        groupedAdapter.setNewData(dataSource);
        groupedTabBarView.smoothScrollToPosition(dataSource.size() - 1);
    }

    private GroupModel newGroupModel() {
        GroupModel localGroupModel = new GroupModel();
        localGroupModel.setGroupId("");
        localGroupModel.setGroupName("");
        localGroupModel.setBrightness(500.0F);
        localGroupModel.setColorTemp(500.0F);
        localGroupModel.setTimeInterval(0L);
        localGroupModel.setFeaturesIndex(-1);
        localGroupModel.setIsSelected(false);
        localGroupModel.setIsOn(false);
        localGroupModel.setSpread(false);
        localGroupModel.setStyle(10);
        return localGroupModel;
    }

    private String generateGroupId() {
        String str = "FE";
        boolean bool1 = false;
        for (byte b = 1; b < 9; b++) {
            str = String.format("%02X", b);
            for (GroupModel model : dataSource) {
                bool1 = false;
                if (model.getGroupId().equals(str)) {
                    bool1 = true;
                    break;
                }
            }
            if (!bool1) {
                return str;
            }
        }
        return str;
    }

}

